"""
缓存工具
"""
import diskcache as dc

cache = dc.Cache('./cache_dir')  # 数据将存储在 ./cache_dir 文件夹中
cache.clear()

def set_file(file_obj):
    if not file_obj:
        return
    set_file_by_type(file_obj.name, file_obj.type, file_obj)


def get_file(file_name):
    files = cache.get(f"file:{file_name}")

    if not files:
        return None

    return files[0]


def list_file(file_name):
    return cache.get(f"file:{file_name}")


def del_file(file_obj):
    if not file_obj:
        return
    file_name = file_obj.name
    names = list_file(file_name)
    if names:
        for name_obj in names:
            if name_obj.token == file_obj.token:
                names.remove(name_obj)
                break
    cache.set(f"file:{file_name}", names)
    # 同步删除类型
    __del_file_by_type(file_obj)
    __del_file_by_token(file_name)


def set_file_by_type(file_name, file_type, file_obj):
    names = list_file(file_name)
    if names:
        names.append(file_obj)
    else:
        names = [file_obj]
    cache.set(f"file:{file_name}", names)

    types = list_file_by_type(file_name, file_type)
    if types:
        types.append(file_obj)
    else:
        types = [file_obj]
    cache.set(f"file_type:{file_name}_{file_type}", types)
    file_token = file_obj.token
    cache.set(f"file_token:{file_token}", file_obj)


def get_file_by_token(file_token):
    return cache.get(f"file_token:{file_token}")


def __del_file_by_token(file_token):
    cache.remove(f"file_token:{file_token}")


def get_file_by_type(file_name, file_type):
    types = cache.get(f"file_type:{file_name}_{file_type}")
    if not types:
        return None
    return types[0]


def list_file_by_type(file_name, file_type):
    return cache.get(f"file_type:{file_name}_{file_type}")


def __del_file_by_type(file_obj):
    file_name = file_obj.name
    file_type = file_obj.type
    types = list_file_by_type(file_name, file_type)
    if types:
        for type_obj in types:
            if type_obj.token == file_obj.token:
                types.remove(type_obj)
                break
    cache.set(f"file_type:{file_name}_{file_type}", types)
